package leetcode;

import java.math.BigInteger;

/**
 * 两个字符串类型的大整数相加(18年被难倒的一道面试题)
 */
public class StrSum {

    public static void main(String[] args) {
        String num1 = "34645734745845856856346457458569", num2 = "23634745856959570";

        String sum1 = sum(num1, num2);
        System.out.println("sum1 = " + sum1);

        //验证
        BigInteger sum2 = new BigInteger(num1).add(new BigInteger(num2));
        System.out.println("sum2 = " + sum2);
    }

    public static String sum(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int max = Math.max(a.length(), b.length());
        char[] as = new StringBuffer(a).reverse().toString().toCharArray();
        char[] bs = new StringBuffer(b).reverse().toString().toCharArray();
        boolean flag = false;
        for (int i = 0; i < max; i++) {
            int j = flag ? 1 : 0;
            flag = false;
            if (i < a.length()) {
                j += as[i] - '0';
            }
            if (i < b.length()) {
                j += bs[i] - '0';
            }
            if (j >= 10) {
                j -= 10;
                flag = true;
            }
            sb.append(j);
        }
        return (flag ? "1" : "") + sb.reverse();
    }
}
